package com.byt.common.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.byt.base.activity.BaseActivity;
import com.byt.base.utils.FileUtil;
import com.byt.base.utils.ToastUitl;
import com.byt.base.utils.onclicktwo.AntiShake;
import com.byt.base.utils.permission.PermissionReq;
import com.byt.base.utils.permission.ResultListener;
import com.byt.base.viewmodel.BaseViewModel;
import com.byt.common.BaseColor;
import com.byt.common.R;
import com.byt.common.databinding.ActivitySelectPictureBinding;
import com.byt.common.image.ImageLoaderUtils;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 图片选择只有一张（可以选择切图或者是不切图）
 */
public class ImageSelectActivity extends BaseActivity<ActivitySelectPictureBinding, BaseViewModel> {
    private int expertsColorInt = Color.parseColor("#79d6db");
    private int userColorInt = Color.parseColor("#ff487d");
    public static final String INP_PACKAGENAME = "PACKAGENAME";
    public static final String INP_SCREENSHOT = "SCREENSHOT";
    public static final String INP_CARD = "CARD";
    public static final String INP_CARD_TYPE = "CARD_TYPE";
    public static final int RESULT_CROP = 1001;
    public static final int RESULT_ERROR = 1000;

    public static final String EXTRA_PATH = "path";
    //保存拍照缓存的Uri和图片名称
    private Uri mTakePhotoUri;
    private String mTackPhotoName;
    private File picfile = null;

    RelativeLayout rl_back_grid;
    protected static String mPhotoTargetFolder;
    boolean isDirShowing = false;
    private View view_layer;
    private TextView tv_title;
    private RecyclerView recycler_image;
    private RecyclerView recycler_dir;
    private ImageAdapter imageAdapter;
    private String packageName = "com.byt.xdoctor";
    private ArrayList<Folder> mDirPaths = new ArrayList<>();
    private int titleColor = userColorInt;

    private RelativeLayout title_rl;
    /**
     * 0、不截取
     * 1、截取圆
     * 2、截取矩形
     */
    private int isScreenshot = 0;
    private Boolean isCard = false;
    private int cardType = 0;

    /**
     * 已选择的图片
     */
    private ArrayList<String> selectedPicture = new ArrayList<>();
    private String cameraPath = null;
    private Folder imageAll, currentImageFolder;
    private FolderAdapter dirAdapter;

    public static void start(Activity context, String pacgName, int isScreenshot) {
        PermissionReq.with(context)
                .permissions(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .result(new ResultListener() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(context, ImageSelectActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra(INP_PACKAGENAME, pacgName);
                        intent.putExtra(INP_SCREENSHOT, isScreenshot);
                        context.startActivity(intent);
                    }

                    @Override
                    public void onDenied() {
                        ToastUitl.showShort("请开启储存权限与相机权限");
                    }
                }).
                request();
    }

    public static void startForResult(Activity context, int flag, String pacgName, int isScreenshot) {
        PermissionReq.with(context)
                .permissions(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .result(new ResultListener() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(context, ImageSelectActivity.class);
                        intent.putExtra(INP_PACKAGENAME, pacgName);
                        intent.putExtra(INP_SCREENSHOT, isScreenshot);
                        context.startActivityForResult(intent, flag);
                    }

                    @Override
                    public void onDenied() {
                        ToastUitl.showShort("请开启储存权限与相机权限");
                    }
                }).
                request();
    }

    public static void startForResult(Activity context, int flag, String pacgName, int isScreenshot, boolean isCard, int isPosition) {
        PermissionReq.with(context)
                .permissions(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .result(new ResultListener() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(context, ImageSelectActivity.class);
                        intent.putExtra(INP_PACKAGENAME, pacgName);
                        intent.putExtra(INP_SCREENSHOT, isScreenshot);
                        intent.putExtra(INP_CARD, isCard);
                        intent.putExtra(INP_CARD_TYPE, isPosition);
                        context.startActivityForResult(intent, flag);
                    }

                    @Override
                    public void onDenied() {
                        ToastUitl.showShort("请开启储存权限与相机权限");
                    }
                }).
                request();
    }

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_select_picture;
    }

    @Override
    protected BaseViewModel getViewModel() {
        return null;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected void initParameters() {
        super.initParameters();
        packageName = getIntent().getStringExtra(INP_PACKAGENAME);
        isScreenshot = getIntent().getIntExtra(INP_SCREENSHOT, 0);
        isCard = getIntent().getBooleanExtra(INP_CARD, false);
        cardType = getIntent().getIntExtra(INP_CARD_TYPE, 0);
        if (packageName.equals("com.byt.xdoctor")) {
            titleColor = userColorInt;
        } else if (packageName.equals("com.szrxy.staff")) {
            titleColor = BaseColor.staff_color_main;
        } else {
            titleColor = expertsColorInt;
        }
        SetStatusBarColor(titleColor);
        title_rl = findViewById(R.id.title_rl_select);
        rl_back_grid = findViewById(R.id.rl_back_select);
        rl_back_grid.setOnClickListener(view -> onBackPressed());
        title_rl.setBackgroundColor(titleColor);
        bindViews();
        initViews();
        bindListeners();
    }

    private void bindViews() {
        view_layer = findViewById(R.id.view_layer_select);
        tv_title = findViewById(R.id.tv_title_select);
        recycler_image = findViewById(R.id.recycler_view_select);
        recycler_dir = findViewById(R.id.recycler_dir_select);
        view_layer.setVisibility(View.GONE);
        recycler_dir.setVisibility(View.GONE);
    }

    private void initViews() {
        imageAll = new Folder();
        imageAll.setDir("/所有图片");
        currentImageFolder = imageAll;
        mDirPaths.add(imageAll);
        getThumbnail();
    }

    private void bindListeners() {
        tv_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleDirlistPop();
            }
        });

        //图片列表
        GridLayoutManager mgr = new GridLayoutManager(this, 3);
        recycler_image.setLayoutManager(mgr);
        recycler_image.addItemDecoration(new GridSpacingItemDecoration(3, dp2px(5), false));
        imageAdapter = new ImageAdapter();
        recycler_image.setAdapter(imageAdapter);

        //目录列表
        recycler_dir.setLayoutManager(new LinearLayoutManager(this));
        dirAdapter = new FolderAdapter();
        recycler_dir.setAdapter(dirAdapter);

        //黑色图层
        view_layer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideDirList();
            }
        });
    }

    private void toggleDirlistPop() {
        if (isDirShowing) {
            hideDirList();
        } else {
            showDirlist();
        }
    }

    private void hideDirList() {
        view_layer.animate().alpha(0).setDuration(300).start();

        recycler_dir.animate().translationY(-dp2px(310)).setDuration(300).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isDirShowing = false;
                view_layer.setVisibility(View.GONE);
                recycler_dir.setVisibility(View.GONE);
            }
        }).start();
    }

    private void showDirlist() {
        view_layer.setVisibility(View.VISIBLE);
        recycler_dir.setVisibility(View.VISIBLE);
        view_layer.animate().alpha(1).setDuration(300).start();
        recycler_dir.animate().translationY(0).setDuration(300).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isDirShowing = true;
            }
        }).start();
    }

    /**
     * 得到缩略图
     */
    private void getThumbnail() {
        /**
         * 临时的辅助类，用于防止同一个文件夹的多次扫描
         */
        HashMap<String, Integer> tmpDir = new HashMap<String, Integer>();

        Cursor mCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.ImageColumns.DATA}, "", null,
                MediaStore.MediaColumns.DATE_ADDED + " DESC");
        Log.e("TAG", mCursor.getCount() + "");
        if (mCursor.moveToFirst()) {
            do {
                // 获取图片的路径
                String path = mCursor.getString(0);
                Log.e("TAG", path);
                File imgFile = new File(path);
                if (imgFile.length() > 0)
                    imageAll.images.add(new ImageItem(path));
                // 获取该图片的父路径名
                if (imgFile.getParentFile() == null) {
                    continue;
                }
                Folder imageFloder;
                String dirPath = imgFile.getParentFile().getAbsolutePath();
                if (!tmpDir.containsKey(dirPath)) {
                    // 初始化imageFloder
                    imageFloder = new Folder();
                    imageFloder.setDir(dirPath);
                    imageFloder.setFirstImagePath(path);
                    mDirPaths.add(imageFloder);
                    Log.d("GridImageActivity", dirPath + "," + path);
                    tmpDir.put(dirPath, mDirPaths.indexOf(imageFloder));
                } else {
                    imageFloder = mDirPaths.get(tmpDir.get(dirPath));
                }
                if (imgFile.length() > 0)
                    imageFloder.images.add(new ImageItem(path));
            } while (mCursor.moveToNext());
        }
        mCursor.close();
        for (int i = 0; i < mDirPaths.size(); i++) {
            Folder f = mDirPaths.get(i);
            Log.d("GridImageActivity", i + "-----" + f.getName() + "---" + f.images.size());
        }
        tmpDir = null;
    }

    private void resetDirList(Folder selectFolder) {
        Folder bufer = new Folder();
        bufer.images.addAll(selectFolder.images);
        bufer.images.add(0, new ImageItem(""));
        bufer.dir = selectFolder.dir;
        bufer.firstImagePath = selectFolder.firstImagePath;
        bufer.name = selectFolder.name;
        currentImageFolder = bufer;
        dirAdapter.notifyDataSetChanged();
        imageAdapter.notifyDataSetChanged();
        hideDirList();
    }

    public int dp2px(int dp) {
        float scale = getResources().getDisplayMetrics().densityDpi;
        return (int) (dp * scale / 160 + 0.5f);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 拍照身份证
      /*  if (requestCode == CameraActivity.REQUEST_CODE && resultCode == CameraActivity.RESULT_CODE) {
            //获取图片路径，显示图片
            final String cardPath = CameraActivity.getImagePath(data);
            if (!TextUtils.isEmpty(cardPath)) {
                Bundle bundle = new Bundle();
                bundle.putString("data", cardPath);
                setResultOk(bundle);
            }
            return;
        }*/
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case UCrop.REQUEST_CROP:
                    if (isScreenshot != 0) {
                        Uri destinationUri = Uri.fromFile(new File(FileUtil.getPicDir(mBContext), mTackPhotoName));
                        onResultCrop(mTakePhotoUri, destinationUri);
                    } else {
                        if (picfile == null) {
                            showShortToast("获取相片失败");
                            this.setResult(RESULT_OK, data);
                        } else {
                            onSaveImage();
                            Bundle bundle = new Bundle();
                            bundle.putString("data", picfile.getAbsolutePath());
                            setResultOk(bundle);
                        }
                        finish();
                    }
                    break;
                case UCrop.RESULT_ERROR:
                    break;
                case RESULT_CROP:
                    this.setResult(RESULT_OK, data);
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

    private void onSaveImage() {
        int degree = readPictureDegree(picfile.getAbsolutePath());
        Uri uri = Uri.fromFile(picfile);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 简单的压缩
        try {
            BitmapFactory.decodeStream(mBContext.getContentResolver().openInputStream(uri), null, options);
            options.inSampleSize = 4;
            options.inJustDecodeBounds = false; // 压缩完后便可以将inJustDecodeBounds设置为false
            // 把流转化为Bitmap图片
            Bitmap bitmap = BitmapFactory.decodeStream(mBContext.getContentResolver().openInputStream(uri), null,
                    options);
            // 根据旋转角度，生成旋转矩阵
            Matrix matrix = new Matrix();
            matrix.postRotate(degree);
            Bitmap returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            picfile = FileUtil.saveBitmap(this, returnBm, "pic_" + new Date().getTime());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    //照相机返回图片后裁切处理
    private void onResultCrop(Uri mTakePhotoUri, Uri destinationUri) {
        UCrop uCrop = UCrop.of(mTakePhotoUri, destinationUri);
        UCrop.Options options = new UCrop.Options();
        options.setCompressionFormat(Bitmap.CompressFormat.PNG);
        options.setStatusBarColor(titleColor);
        options.setToolbarColor(titleColor);
        options.setToolbarWidgetColor(Color.WHITE);
        if (isScreenshot == 1) {
            uCrop.withAspectRatio(1, 1);
            options.setCircleDimmedLayer(true);
            options.setShowCropFrame(false);
            options.setShowCropGrid(false);
            options.setHideBottomControls(true);
            options.setFreeStyleCropEnabled(false);
        } else if (isScreenshot == 2) {
            uCrop.withAspectRatio(1, 1);
            options.setHideBottomControls(true);
            options.setFreeStyleCropEnabled(true);
        } else if (isScreenshot == 3) {
            uCrop.withAspectRatio(16, 9);
            options.setHideBottomControls(true);
            options.setFreeStyleCropEnabled(false);
        } else if (isScreenshot == 4) {
            uCrop.withAspectRatio(5, 2);
            options.setHideBottomControls(true);
            options.setFreeStyleCropEnabled(false);
        } else {
            uCrop.withAspectRatio(1, 1);
            options.setHideBottomControls(true);
            options.setFreeStyleCropEnabled(false);
        }
        uCrop.withOptions(options);
        uCrop.start(ImageSelectActivity.this, this.RESULT_CROP);
    }

    class ImageAdapter extends RecyclerView.Adapter<ImageViewHolder> {

        @Override
        public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == 0) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo_list_camera, parent, false);
                return new ImageViewHolder(view);
            }
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false);
            return new ImageViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ImageViewHolder holder, int position) {
            if (position == 0) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AntiShake.check(v.getId())) {
                            return;
                        }
                        takePhotoAction();
                    }
                });
                return;
            } else {
                final ImageItem item = currentImageFolder.images.get(position);
                ImageLoaderUtils.display(holder.imageView, item.path);
                holder.tv_click.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AntiShake.check(v.getId())) {
                            return;
                        }
                        String destinationFileName = item.path.hashCode() + ".JPEG";
                        if (!isWebpImage(item.path)) {
                            showShortToast("不支持此格式的图片");
                            return;
                        }
                        Uri sourceUri = Uri.fromFile(new File(item.path));
                        Uri destinationUri = Uri.fromFile(new File(FileUtil.getPicDir(mBContext), destinationFileName));
                        if (isScreenshot != 0) { // 如果截屏的话
                            onResultCrop(sourceUri, destinationUri);
                        } else {
                            Intent intent = new Intent();
                            intent.putExtra("data", item.path);
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }
                });
            }
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            return currentImageFolder.images.size();
        }
    }

    private boolean isWebpImage(String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        String type = options.outMimeType;
        if (TextUtils.isEmpty(type)) {
            type = "未能识别的图片";
            return false;
        } else {
            type = type.substring(6, type.length());
            Log.d("image type -> ", type);
            if (type.equals("webp")) {
                return false;
            } else {
                return true;
            }
        }

    }

    class ImageViewHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;
        public View tv_click;

        public ImageViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.iv);
            tv_click = itemView.findViewById(R.id.tv_click);
        }

    }

    class FolderAdapter extends RecyclerView.Adapter<FolderViewHolder> {
        @Override
        public FolderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dir, parent, false);
            return new FolderViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FolderViewHolder holder, int position) {
            final Folder item = mDirPaths.get(position);
            ImageLoaderUtils.display(holder.iv_dir, item.getFirstImagePath());
            String name = item.name.startsWith("/") ? item.name.substring(1) : item.name;
            holder.tv_dirname.setText(name + " (" + (item.images.size()) + "张) ");
            holder.ll_root.setSelected(currentImageFolder == item);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (AntiShake.check(v.getId())) {
                        return;
                    }
                    resetDirList(item);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mDirPaths.size();
        }
    }

    class FolderViewHolder extends RecyclerView.ViewHolder {

        public ImageView iv_dir;
        public TextView tv_dirname;
        public View ll_root;

        public FolderViewHolder(View itemView) {
            super(itemView);
            ll_root = itemView.findViewById(R.id.ll_root);
            iv_dir = itemView.findViewById(R.id.iv_dir);
            tv_dirname = itemView.findViewById(R.id.tv_dirname);
        }
    }

    /**
     * 拍照
     */
    protected void takePhotoAction() {
        File takePhotoFolder;
        if (TextUtils.isEmpty(mPhotoTargetFolder)) {
            takePhotoFolder = new File(FileUtil.getPicDir(mBContext));
        } else {
            takePhotoFolder = new File(mPhotoTargetFolder);
        }
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        mTackPhotoName = f.format(new Date());
        picfile = new File(takePhotoFolder, "IMG" + mTackPhotoName + ".jpg");
        boolean suc = false;
        try {
            suc = picfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (suc) {
            mTakePhotoUri = FileProvider.getUriForFile(mBContext, packageName + ".fileprovider", picfile);
           /* if (isCard) {
                if (cardType == 0) {
                    CameraActivity.toCameraActivity(this, CameraActivity.TYPE_IDCARD_FRONT);
                } else {
                    CameraActivity.toCameraActivity(this, CameraActivity.TYPE_IDCARD_BACK);
                }
            } else {*/
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            startActivityForResult(captureIntent, UCrop.REQUEST_CROP);
//            }
        } else {
            showShortToast("创建文件失败");
        }
    }

    class Folder {

        public List<ImageItem> images = new ArrayList<ImageItem>();
        /**
         * 图片的文件夹路径
         */
        private String dir;
        /**
         * 第一张图片的路径
         */
        private String firstImagePath;
        /**
         * 文件夹的名称
         */
        private String name;

        public String getDir() {
            return dir;
        }

        public void setDir(String dir) {
            this.dir = dir;
            int lastIndexOf = this.dir.lastIndexOf("/");
            this.name = this.dir.substring(lastIndexOf);
        }

        public String getFirstImagePath() {
            return firstImagePath;
        }

        public void setFirstImagePath(String firstImagePath) {
            this.firstImagePath = firstImagePath;
        }

        public String getName() {
            return name;
        }

    }

    class ImageItem {

        String path;

        Boolean isCheck;

        public Boolean getCheck() {
            return isCheck;
        }

        public void setCheck(Boolean check) {
            isCheck = check;
        }

        public ImageItem(String p) {
            this.path = p;
        }

    }

    class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }
}
